<?php

namespace addons\wxfollowlogin\controller;

use addons\wxfollowlogin\model\WxfollowloginScene;
use addons\wxfollowlogin\library\Service;
use EasyWeChat\Factory;
use think\addons\Controller;
use think\Log;

class Api extends Controller
{

    /**
     * 接口对接
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \ReflectionException
     */
    public function index()
    {
        $config = get_addon_config('wxfollowlogin');
        $config = [
            'app_id' => $config['appid'],
            'secret' => $config['appsecret'],
            'token' => $config['token'],
            'aes_key' => $config['encodingaeskey'],
            'response_type' => 'array',
        ];

        $app = Factory::officialAccount($config);
        $app->server->push(function ($message) use ($app) {
            Log::info($message);
            switch ($message['MsgType']) {
                case 'event':
                    if (!empty($message['EventKey'])) {
                        $eventKey = $message['EventKey'];
                        $scene_id = str_replace("qrscene_", "", $eventKey);
                        $openid =  $message['FromUserName']; //openid
                        $userInfo = $app->user->get($openid);

                        WxfollowloginScene::update(array('openid' => $openid, 'login_time' => time()), ['id' => $scene_id]);
                        Service::connect(array('openid' => $openid, 'avatar' => $userInfo['headimgurl'], 'nickname' => $userInfo['nickname']));
                        return "恭喜您，登录成功";
                    }
                    break;
                case 'text':

                    $content = trim($message['Content'],"");
                    $scene = WxfollowloginScene::get(['openid'=>'','scene_id'=>$content,'createtime'=>['gt',time()-60]]);

                    if($scene){
                        $openid =  $message['FromUserName']; //openid
                        $userInfo = $app->user->get($openid);

                        $headimgurl = empty($userInfo['headimgurl'])?'':$userInfo['headimgurl'];
                        $nickname = empty($userInfo['nickname'])?'':$userInfo['nickname'];

                        WxfollowloginScene::update(array('openid'=>$openid,'login_time'=>time()),['id'=>$scene->id]);
                        Service::connect(array('openid'=>$openid,'avatar'=>$headimgurl,'nickname'=>$nickname));
                        return "恭喜您，登录成功!";
                    }
                    break;
            }
        });

        $response = $app->server->serve();
        $response->send();
    }

}
